<template>
  <div class="container">
    <div class="app-container">
      <div class="role-operate">
        <el-button
          size="mini"
          type="primary"
          @click="showDialog = true;isAdd=true"
        >添加角色</el-button>
      </div>
      <el-table v-loading="loading" :data="list" style="width: 100%">
        <el-table-column prop="name" label="角色" width="200">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="启用" width="200">
          <template v-slot="{ row }">
            <el-switch
              v-if="row.isEdit"
              v-model="row.state"
              size="mini"
              :active-value="1"
              :inactive-value="0"
            />
            <span>
              {{
                row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无"
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述">
          <template v-slot="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="btnRowOK(row)">确定</el-button>
              <el-button size="mini" @click="btnRowCancel(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <!-- <el-button size="mini" type="text" @click="showEdit(row.id)">编辑</el-button> -->
              <el-button v-if="hasPerm('edit-role')" size="mini" type="text" @click="showEdit(row)">编辑</el-button>
              <el-popconfirm v-if="hasPerm('edit-role')" title="这是一段内容确定删除吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" size="mini" type="text" style="margin-left:10px">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" style="height: 60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          layout="prev, pager, next"
          :page-size="pageParams.pagesize"
          :total="pageParams.total"
          :current-page="pageParams.page"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <el-dialog :visible.sync="showDialog" :title="isAdd?'新增角色':'编辑角色'" width="500px" @close="btnCancel">
      <el-form
        ref="roleForm"
        label-width="120px"
        :rules="rules"
        :model="roleForm"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" style="width: 300" size="mini" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch
            v-model="roleForm.state"
            size="mini"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item v-model="roleForm.description" label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            style="width: 300px"
            size="mini"
            :rows="3"
          />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 放置权限弹层 -->
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限">
      <!-- 放置权限数据 -->
      <el-tree
        ref="permTree"
        node-key="id"
        :data="permissionData"
        :props="{ label: 'name' }"
        show-checkbox
        default-expand-all
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
        <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { addRole, getRoleList, updataRole, delRole, getRole, assignPerm } from '@/api/role'
import { transListToTreeData } from '@/utils/index'
import { getPermissionList } from '@/api/permission'
export default {
  name: 'Role',
  data() {
    return {
      loading: false,
      roleForm: {
        name: '',
        description: '',
        state: 0// 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      list: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      showDialog: false,
      isAdd: true,
      // 分配权限弹层变量
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows
      this.pageParams.total = total
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state// 默认未1启用 关闭 0 打开1
        })
      })
      // console.log(this.list)
      this.loading = false
    },
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
    },
    btnCancel() {
      this.roleForm = this.$options.data().roleForm
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    btnOK() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          if (this.isAdd) {
            await addRole(this.roleForm)
            this.$message.success('新增角色成功')
          } else {
            // await updataRole(this.roleForm.id, this.roleForm)
            await updataRole(this.roleForm)
            this.$message.success('编辑角色成功')
          }

          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    // async showEdit(id) {
    //   const data = await getRole(id)
    //   this.roleForm = data
    //   this.isAdd = false
    //   this.showDialog = true
    // },
    showEdit(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async btnRowOK(row) {
      if (row.editRow.name && row.editRow.description) {
        await updataRole({
          id: row.id,
          ...row.editRow
        })
        this.$message.success('更新数据成功')
        Object.assign(row, row.editRow)
        // eslint-disable-next-line require-atomic-updates
        row.isEdit = false
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    btnRowCancel(row) {
      row.isEdit = false
    },
    async confirmDel(id) {
      await delRole(id)
      this.$message.success('删除角色成功')
      if (this.list.length === 1) this.pageParams.page--
      this.getRoleList()
    },
    // 分配权限弹层显示
    async btnPermission(id) {
      this.currentRoleId = id
      const { permIds } = await getRole(id)
      this.permIds = permIds
      this.permissionData = transListToTreeData(await getPermissionList(), 0)
      this.showPermissionDialog = true
    },
    // 分配权限确定
    async btnPermissionOK() {
      await assignPerm({
        id: this.currentRoleId,
        permIds: this.$refs.permTree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPermissionDialog = false
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
